package com.cuit.utils;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author cfy
 * @date 2022/12/1 22:20
 * @desciption: 文件上传
 */
@Slf4j
@Component
public class UploadFile {

    /**
     * 文件上传用的工具类
     * @author cfy
     * @date 2022/12/1 22:29
     * @param file
     * @param uploadPath
     * @return FileUtils
     */
    public FileUtils upload(MultipartFile file,String uploadPath) throws IOException {
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名字.....................{}",originalFilename);
        String contentType = file.getContentType();
        log.info("contentType--------------->{}",contentType);
        String type = FileUtil.extName(originalFilename);
        log.info("通过hutool获得文件类型------>{}",type);
        long size = file.getSize();
        log.info("文件大小------>{}",size);
        // 先存到磁盘
        File uploadFile = new File(uploadPath);
        // 判断配置的文件目录是否存在，不存在创建新的文件
        if (!uploadFile.exists()){
            uploadFile.mkdirs();
        }
        String fileUUID = UUID.randomUUID().toString().replace("-", "");
        //eg: UUID + . + png
        String fileName = fileUUID + "." + type;  // 创建文件名称
        String filePath = uploadPath + "/" + fileName; // 文件的路径
        File file2 = new File(filePath);

        // 进行文件的白名单校验
        FileUtils fileUtils = new FileUtils();
        // 将获得数据保存到磁盘
        file.transferTo(file2);
        // 设置存入数据的对象
        fileUtils.setFileUrl(filePath);
        fileUtils.setFileName(originalFilename);
        fileUtils.setFileUUIDName(fileName);
        return fileUtils;
    }
}
